import { defineStore } from 'pinia'
import { computed, ref } from 'vue'

const useLoadState = defineStore('loadState', () => {
  /**
   * 请求数量
   */
  const requestNumber = ref(0)
  /**
   * 请求接口键值对
   */
  const opNames = ref<Record<string, boolean>>({})

  /**
   * 全局是否有接口正在请求
   */
  const isLoading = computed(() => requestNumber.value > 0)

  /**
   * 查询某个接口是否正在请求
   */
  const isOpLoading = (opName: string) => computed(() => opNames.value[opName] || false)
  
  /**
   * 某个接口开始请求
   * @param opName 接口地址
   */
  function startLoading(opName?: string) {
    requestNumber.value++
    if (opName) opNames.value[opName] = true
  }
  /**
   * 某个接口结束请求
   * @param opName 接口地址
   */
  function finishLoading(opName?: string) {
    requestNumber.value--
    if (opName) delete opNames.value[opName]
  }

  return { requestNumber, opNames, isLoading, isOpLoading, startLoading, finishLoading }
})

export default useLoadState
